package data

import (
	"context"
	"kra/cmd/gorm/dal/repository"
	"kra/internal/conf"
	"time"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/wire"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewGreeterRepo, NewRedisCmd, NewAppUseCase)

// Data .
type Data struct {
	Db       *gorm.DB
	Q        *repository.Query
	Log      *log.Helper
	RedisCli redis.Cmdable
}

// NewData .
func NewData(c *conf.Data, logger log.Logger, redisCli redis.Cmdable) (*Data, func(), error) {
	db, err := gorm.Open(mysql.Open(c.Database.Source), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
		panic(err)
	}
	q := repository.Use(db)
	d := &Data{
		Db:       db,
		Q:        q,
		Log:      log.NewHelper(logger),
		RedisCli: NewRedisCmd(c),
	}

	cleanup := func() {
		log.NewHelper(logger).Info("closing the data resources")
	}
	return d, cleanup, nil
}

// NewRedisCmd redis的链接
func NewRedisCmd(conf *conf.Data) redis.Cmdable {
	client := redis.NewClient(&redis.Options{
		Addr:         conf.Redis.Addr,
		ReadTimeout:  conf.Redis.ReadTimeout.AsDuration(),
		WriteTimeout: conf.Redis.WriteTimeout.AsDuration(),
		DialTimeout:  time.Second * 2,
		PoolSize:     10,
	})
	timeout, cancelFunc := context.WithTimeout(context.Background(), time.Second*2)
	defer cancelFunc()
	err := client.Ping(timeout).Err()
	if err != nil {
		log.Fatalf("redis connect error: %v", err)
	}
	return client
}

// NewDiscovery 服务发现
// func NewDiscovery(conf *conf.Data) registry.Discovery {
// 	sc := []constant.ServerConfig{
// 		{
// 			IpAddr: conf.Nacos.Addr,
// 			Port:   conf.Nacos.Port,
// 		},
// 	}
// 	cc := constant.ClientConfig{
// 		NamespaceId: conf.Nacos.NamespaceId,
// 		TimeoutMs:   5000,
// 	}

// 	client, err := clients.NewNamingClient(
// 		vo.NacosClientParam{
// 			ClientConfig:  &cc,
// 			ServerConfigs: sc,
// 		},
// 	)

// 	if err != nil {
// 		panic(err)
// 	}

// 	r := nacos.New(client)
// 	return r
// }

// NewOrderServiceClient orders 服务客户端
// func NewOrderServiceClient(r registry.Discovery) orders.OrderClient {
// 	conn, err := grpc.DialInsecure(
// 		context.Background(),
// 		grpc.WithEndpoint("discovery:///orders-xgs.grpc"),
// 		grpc.WithDiscovery(r),
// 		grpc.WithTimeout(time.Second*2),
// 		grpc.WithMiddleware(
// 			recovery.Recovery(),
// 		),
// 	)
// 	if err != nil {
// 		panic(err)
// 	}
// 	c := orders.NewOrderClient(conn)
// 	return c
// }
